﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;

namespace ScreenProtector
{
    public partial class FrmScreenProtector : Form
    {
        /// <summary>
        /// 设置启动屏保的时间，启动阀值，单位：秒
        /// </summary>
        private int ShowMeTime_threshold_pub = 4;
        private Label lblTime = new Label();//显示时间
        /// <summary>
        /// 进入屏保的倒计时，每秒自动减1
        /// </summary>
        private int ShowMeCountDown_pub;
        /// <summary>
        /// //鼠标的位置
        /// </summary>
        private Point mouseP = new Point();
        /// <summary>
        /// // 声明一个hook对象，勾子
        /// </summary>
        GlobalHook hook;
        /// <summary>
        /// 是否成功启动勾子hook
        /// </summary>
        private bool hook_Enable;
        /// <summary>
        /// //测试时防止错误，自动关闭。
        /// </summary>
        private int testClosing = 30;  
        /// <summary>
        /// 是否移动鼠标退出屏保
        /// </summary>
        bool IsMounseMovingCheck = true;
        /// <summary>
        /// 是否按下键盘退出屏保
        /// </summary>
        bool IsKeyboardPressCheck = true;
        /// <summary>
        /// 退出屏保是否需要密码
        /// </summary>
        bool IsPasswordShow = false;
        public FrmScreenProtector()
        {
            InitializeComponent();
            hook_Enable = false;
        }

        /// <summary>
        /// 调用系统API函数操作鼠标指针，隐藏或显示鼠标指针<para></para>
        /// 0表示隐藏鼠标指针，1表示显示鼠标指针
        /// </summary>
        /// <param name="status">0表示隐藏鼠标指针，1表示显示鼠标指针</param>
        [DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)]        
        public extern static void ShowCursor(int status);

        private void FrmScreenProtector_Load(object sender, EventArgs e)
        {
            this.Hide();
            //ChoiceCountdown(分钟ToolStripMenuItem9);
            //ChoiceOpacity(toolStripMenuItem5);
            //this.BackColor
            //this.label1.ForeColor
            ShowMeCountDown_pub = ShowMeTime_threshold_pub;
            if (hook == null)
            {
                hook = new GlobalHook();
                hook.KeyDown += new KeyEventHandler(hook_KeyDown);
                //hook.KeyPress += new KeyPressEventHandler(hook_KeyPress);
                //hook.KeyUp += new KeyEventHandler(hook_KeyUp);
                //hook.OnMouseActivity += new MouseEventHandler(hook_OnMouseActivity);
                bool r = hook.Start();
                if (r)
                {
                    notifyIcon1.ShowBalloonTip(6000, "启动成功",
                        "按任意键或移动鼠标，屏幕程序重新倒计时。", ToolTipIcon.Info);
                    hook_Enable = true;
                }
                else
                {
                    notifyIcon1.ShowBalloonTip(6000, "程序失败",
                        "按下键盘无法刷新倒计时，鼠标移动才屏幕程序能重新倒计时。", ToolTipIcon.Warning);
                    return;
                }
            }
        }
        
        #region 屏幕保护的隐藏
        /// <summary>
        /// 程序窗口点击鼠标的事件。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmScreenProtector_Click(object sender, EventArgs e)
        {
            //if (this.Visible && IsMounseMovingCheck)
            //    HideForm();
        }
        /// <summary>
        /// 程序窗口按下键盘的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmScreenProtector_KeyDown(object sender, KeyEventArgs e)
        {
            if (IsKeyboardPressCheck && !this.Visible)
                ShowMeCountDown_pub = ShowMeTime_threshold_pub;
        }
        /// <summary>
        /// 接收程序以外的按键信息。
        /// 本程序非恶意程序，该键盘监控是为了刷新倒计时。
        /// 任意键盘事件，倒计时重新刷时间到阀值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hook_KeyDown(object sender, KeyEventArgs e)
        {
            GlobalHook h = (GlobalHook)sender;
            h.HKeyboardHook.ToString();//勾子的键盘状态
            if (IsKeyboardPressCheck)
            {
                if (this.Visible) HideForm();
                else ShowMeCountDown_pub = ShowMeTime_threshold_pub;
            }
        }
        /// <summary>
        /// HideForm()接收外部信息的开关。防止重复调用此函数
        /// </summary>
        private static bool Request = true;
        /// <summary>
        /// 隐藏窗口
        /// </summary>
        private void HideForm()
        {
            if (!Request) return;
            Request = !Request;//暂停接收信息，防止重复调用此函数
            this.TopMost = false;
            ShowCursor(1);//显示鼠标指针
            if (IsPasswordShow)
            {
                string password = Interaction.InputBox("请输入密码", "密码", "123", -1, -1);
                int err = 0;//输入错误密码次数
                while (password != "123")
                {
                    err++;
                    password = Interaction.InputBox("请输入密码", "密码", "123", -1, -1);
                }
            }
            this.TopMost = true;
            if (this.Visible) this.Hide();
            ShowMeCountDown_pub = ShowMeTime_threshold_pub;//重置倒计时
            Request = true;//开放接收信息
        }
        #endregion
        /// <summary>
        /// 定时器的功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                //测试时防止错误，30秒后关闭
                testClosing--;
                if (testClosing <= 0)
                {
                    timer1.Enabled = false;
                    MessageBox.Show("测试时，防止程序崩溃的自动倒计时已经到了。正在退出程序。");
                    Application.Exit();
                }
                //移动鼠标可以退出屏保的开关：
                if (IsMounseMovingCheck)
                {
                    //判断鼠标是否移动
                    if (mouseP.X != Cursor.Position.X || mouseP.Y != Cursor.Position.Y)
                    {
                        HideForm();
                        return;
                    }
                }
            }
            else
            {
                //移动鼠标可以退出屏保的开关：
                if (IsMounseMovingCheck)
                {
                    //判断鼠标是否移动
                    if (mouseP.X != Cursor.Position.X || mouseP.Y != Cursor.Position.Y)
                    {
                        ShowMeCountDown_pub = ShowMeTime_threshold_pub;//重置屏保阀值
                        mouseP = Cursor.Position;
                        return;
                    }
                }
            }

            //无鼠标键盘操作，则进入倒计时
            if (ShowMeCountDown_pub > 0) ShowMeCountDown_pub--;
            //倒计时为0则启动屏幕保护
            if (ShowMeCountDown_pub <= 0)
            {
                string h = DateTime.Now.Hour.ToString("D2");
                string m = DateTime.Now.Minute.ToString("D2");
                string s = DateTime.Now.Second.ToString("D2");
                label1.Left = (this.Width - label1.Width) / 2;
                label1.Top = (this.Height - label1.Height) / 2;
                label1.Text = h + ":" + m + ":" + s;
                //ShowCursor(0);//隐藏鼠标指针
                this.Show();
            }
        }
        /// <summary>
        /// 窗体的透明度 - 选项菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            ChoiceOpacity((ToolStripMenuItem)sender);
        }
        /// <summary>
        /// 设置右键菜单单选
        /// </summary>
        /// <param name="target_item">参数-右键可选项类</param>
        private void ChoiceOpacity(ToolStripMenuItem target_item)
        {
            ToolStripMenuItem father = 不透明度ToolStripMenuItem;
            foreach (ToolStripMenuItem item in father.DropDownItems)
            {
                if (target_item.Text == item.Text)
                {
                    item.Checked = true;
                    string tmp = item.Text.Substring(0, item.Text.Length - 1);
                    float f = float.Parse(tmp) / 100;
                    this.Opacity = f;
                }
                else
                {
                    item.Checked = false;
                }
            }
        }
        // 背景颜色 - 选项菜单
        private void 背景颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            this.BackColor = colorDialog1.Color;
            this.Show();
        }
        //退出程序 - 选项菜单
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        //字体颜色 - 选项菜单
        private void 字体颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            this.label1.ForeColor = colorDialog1.Color;
            this.Show();
        }
        /// <summary>
        /// 启动倒计时 - 选项菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 分钟ToolStripMenuItem9_Click(object sender, EventArgs e)
        {
            ChoiceCountdown((ToolStripMenuItem)sender);
        }
        private void ChoiceCountdown(ToolStripMenuItem target_item)
        {
            ToolStripMenuItem father = 启动时间ToolStripMenuItem;
            foreach (ToolStripMenuItem item in father.DropDownItems)
            {
                if (target_item.Text == item.Text)
                {
                    item.Checked = true;
                    ShowMeTime_threshold_pub = int.Parse(item.Tag.ToString()) * 60;
                }
                else
                    item.Checked = false;
            }
        }

        private void FrmScreenProtector_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (hook_Enable)
            {
                hook.Stop();
            }
            ShowCursor(1);//显示鼠标指针
        }

        public EventHandler input_VisibleChanged { get; set; }
    }
}